package com.lee.blepwm.activity;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.ble.BluetoothLeService;
import com.kongqw.rockerlibrary.view.RockerView;
import com.lee.blepwm.R;
import com.lee.blepwm.utils.HexUtils;
import com.lee.blepwm.view.VerticalSeekBar;

/**
 * declaration:
 * time:
 */
public class ControlActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {

    private static final String TAG = "ControlActivity: ";

    private View vBack;
    private View vSetting;
    private RockerView rockerView;
    private VerticalSeekBar seekBar;

    private Context mContext;
    private BluetoothDevice device;

    private SeekBar seekBar1;
    private SeekBar seekBar2;
    private SeekBar seekBar3;
    private TextView tvSeek1;
    private TextView tvSeek2;
    private TextView tvSeek3;
    private TextView tvConnectStatus;

    private boolean mConnected = false;

    private int middle = 0;
    private int low = 0;
    private int high = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ScreenUtils.setFullScreen(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.control_activity);
        mContext = this;

        Bundle extras = getIntent().getExtras();
        device = extras.getParcelable("blue");

        rockerView = findViewById(R.id.rockerView);
        rockerView.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_MOVE);
        seekBar = findViewById(R.id.seek_bar);
        seekBar1 = findViewById(R.id.seek_bar1);
        seekBar2 = findViewById(R.id.seek_bar2);
        seekBar3 = findViewById(R.id.seek_bar3);
        tvSeek1 = findViewById(R.id.tv_seek1);
        tvSeek2 = findViewById(R.id.tv_seek2);
        tvSeek3 = findViewById(R.id.tv_seek3);
        vBack = findViewById(R.id.v_back);
        vSetting = findViewById(R.id.v_setting);
        tvConnectStatus = findViewById(R.id.tv_connect_status);
        tvConnectStatus.setText("等待连接...");

        middle = ConvertUtils.hexString2Int("13");
        low = ConvertUtils.hexString2Int("10");
        high = ConvertUtils.hexString2Int("17");

        initListener();
        mDeviceAddress = device.getAddress();

        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }

        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        sg = bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
        LogUtils.e("sg : " + sg);
    }

    private BluetoothLeService mBluetoothLeService;
    private boolean sg;
    private String mDeviceAddress;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    //                        or notification operations.
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                tvConnectStatus.setText("连接成功");
                LogUtils.e("连接成功");

//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                mBluetoothLeService.set_PWM_frequency(50);//设置PWM频率
//                delay();
//                mBluetoothLeService.set_PWM_OPEN(1);//打开PWM
//                delay();
//                //初始化占空比
//                mBluetoothLeService.set_PWM1_pulse(19); // 75%占空比
//                delay();
//                mBluetoothLeService.set_PWM2_pulse(19); // 75%占空比
//                delay();
//                mBluetoothLeService.set_PWM3_pulse(12);//0c-19（十进制13-25）
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {

                LogUtils.e("连接失败/断开");
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                mBluetoothLeService.set_PWM_frequency(50);//设置PWM频率
                delay();
                mBluetoothLeService.set_PWM_OPEN(1);//打开PWM
                delay();
                //初始化占空比
                mBluetoothLeService.set_PWM1_pulse(19); // 75%占空比
                delay();
                mBluetoothLeService.set_PWM2_pulse(19); // 75%占空比
                delay();
                mBluetoothLeService.set_PWM3_pulse(12);//0c-19（十进制13-25）
                delay();
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                //接收FFE1串口透传数据

            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE1.equals(action)) {
                //接收FFE2功能配置返回数据
                displayData1(intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA1));
            }
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE1);
        return intentFilter;
    }

    private void initListener() {
//        rockerView.setOnShakeListener(RockerView.DirectionMode.DIRECTION_4_ROTATE_45, new RockerView.OnShakeListener() {
//            @Override
//            public void onStart() {
//            }
//
//            @Override
//            public void direction(RockerView.Direction direction) {
////                DIRECTION_LEFT 	左
////                DIRECTION_RIGHT 	右
////                DIRECTION_UP 	上
////                DIRECTION_DOWN 	下
////                DIRECTION_UP_LEFT 	左上
////                DIRECTION_UP_RIGHT 	右上
////                DIRECTION_DOWN_LEFT 	左下
////                DIRECTION_DOWN_RIGHT 	右下
////                DIRECTION_CENTER 	中间
//                /**
//                 * PWM1/PWM2
//                 * 倒  0b-12(快-慢)  12--18
//                 *      12--自检点
//                 * 进   12--19(慢-快)  18 - 25
//                 */
//                if (!mConnected)
//                    return;
//                switch (direction) {
//                    case DIRECTION_LEFT:
//                        mBluetoothLeService.set_PWM1_pulse(22);
//                        delay();
//                        mBluetoothLeService.set_PWM2_pulse(14);
//                        break;
//                    case DIRECTION_RIGHT:
//                        mBluetoothLeService.set_PWM1_pulse(14);
//                        delay();
//                        mBluetoothLeService.set_PWM2_pulse(22);
//                        break;
//                    case DIRECTION_UP:
//                        mBluetoothLeService.set_PWM2_pulse(25);
//                        delay();
//                        mBluetoothLeService.set_PWM1_pulse(25);
//                        break;
//                    case DIRECTION_DOWN:
//                        mBluetoothLeService.set_PWM1_pulse(12);
//                        delay();
//                        mBluetoothLeService.set_PWM2_pulse(12);
//                        break;
//                    default:
//                        break;
//                }
//            }
//
//            @Override
//            public void onFinish() {
//                if (!mConnected)
//                    return;
//                delay();
//                mBluetoothLeService.set_PWM1_pulse(19);
//                delay();
//                mBluetoothLeService.set_PWM2_pulse(19);
//            }
//        });

        rockerView.setOnAngleChangeListener(new RockerView.OnAngleChangeListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void angle(double angle, int mRockerRadius, float xy) {
                if (!mConnected)
                    return;
                /**
                 * PWM1/PWM2
                 * 倒  0b-12(快-慢)  12--16
                 *      16--自检点
                 * 进   12--19(慢-快)  16 - 25
                 */
                float location = mRockerRadius;
                if (xy < mRockerRadius) {
                    location = xy;
                }
                int s = (int) (location / mRockerRadius * (low - middle - 1));
                int s2 = (int) (location / mRockerRadius * (high - middle + 1));

                int pwm1 = 0, pwm2 = 0;

                if (angle > 45 && angle < 135) {
                    // down
                    pwm1 = pwm2 = s + middle;
                } else if (angle > 135 && angle < 225) {
                    // left
                    pwm1 = s2 - 2 + middle;
                    pwm1 = 21;
//                    pwm2 = s+ middle;
                } else if (angle > 225 && angle < 315) {
                    //up
                    pwm1 = pwm2 = s2 + middle;
                } else {
                    //right
//                    pwm1 = s+ middle;
                    pwm2 = s2 - 2 + middle;
                    pwm2 = 21;
                }
                LogUtils.d("location: " + location + "---s: " + s + "---pwm1: " + pwm1 + "---pwm2: " + pwm2);

                delay();
                mBluetoothLeService.set_PWM1_pulse(pwm1);
                delay();
                mBluetoothLeService.set_PWM2_pulse(pwm2);
            }

            @Override
            public void onFinish() {
                if (!mConnected)
                    return;
                delay();
                mBluetoothLeService.set_PWM1_pulse(middle);
                delay();
                mBluetoothLeService.set_PWM2_pulse(middle);
            }
        });
        seekBar.setOnSeekBarChangeListener(this);
        seekBar1.setOnSeekBarChangeListener(this);
        seekBar2.setOnSeekBarChangeListener(this);
        seekBar3.setOnSeekBarChangeListener(this);

        vBack.setOnClickListener(view -> {
            finish();
        });
        vSetting.setOnClickListener(view -> {
            if (!mConnected) {
                ToastUtils.showShort("连接没有成功");
                return;
            }
            // TIP 设置参数
//            mBluetoothLeService.set_name("16");
//            delay();
            mBluetoothLeService.set_PWM_frequency(50);//设置PWM频率
            delay();
            mBluetoothLeService.set_PWM_OPEN(1);//打开PWM
            delay();
            //初始化占空比
            mBluetoothLeService.set_PWM1_pulse(19); // 75%占空比
            delay();
            mBluetoothLeService.set_PWM2_pulse(19); // 75%占空比
            delay();
            mBluetoothLeService.set_PWM3_pulse(12);//0c-19（十进制13-25）
//            mBluetoothLeService.set_PWM4_pulse(12);//0c-19
        });
    }

    private void displayData1(byte[] data1) {
        //接收FFE2功能配置返回的数据
        String str = mBluetoothLeService.bytesToHexString1(data1);//将接收的十六进制数据转换成十六进制字符串
        LogUtils.d(str);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        switch (seekBar.getId()) {
            case R.id.seek_bar:
                // 十进制12-25(0c-19)
                /**
                 * PWM3
                 * 0C--最低   12
                 * 19 --最高   25
                 */
                /**
                 * PWM1/PWM2
                 * 倒  0b-12(快-慢)  11--16
                 *      16--自检点
                 * 进   12--19(慢-快)  16 - 25
                 */
                if (progress > 11 && progress < 26) {
                    mBluetoothLeService.set_PWM3_pulse(progress);
                } else {
                    mBluetoothLeService.set_PWM3_pulse(12);
                }
                break;
            case R.id.seek_bar1:
                setData(tvSeek1, progress, "E8a3");
                mBluetoothLeService.set_PWM1_pulse(progress);
                break;
            case R.id.seek_bar2:
                setData(tvSeek2, progress, "E8a4");
                mBluetoothLeService.set_PWM2_pulse(progress);
                break;
            case R.id.seek_bar3:
                // 十进制12-25
                setData(tvSeek3, progress, "E8a5");
                if (progress > 11 && progress < 26) {
                    mBluetoothLeService.set_PWM3_pulse(progress);
                } else {
                    mBluetoothLeService.set_PWM3_pulse(11);
                }
                break;
        }

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    private void setData(TextView tv, int progress, String txt) {
        String vs = String.format("%02X", progress);
        txt = txt + vs;
        tv.setText(String.format("占空比:%s    十六进制:%s", progress / 255F * 100F, txt.toUpperCase()
        ));
    }

    private void delay() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConnected) {
            mBluetoothLeService.disconnect();
            unregisterReceiver(mGattUpdateReceiver);
            unbindService(mServiceConnection);
            mBluetoothLeService = null;
        }
    }
}
